package cc.messcat.web.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cc.messcat.entity.area.Area;
import cc.messcat.service.area.AreaService;
import cc.messcat.util.Collections;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 行政区域切面类
 */
@Aspect
@Component
public class AreaAspect {
	
	@Autowired
	private CacheManager manager;

	@Autowired
	private AreaService areaService;
	private static final Logger logger = LoggerFactory.getLogger(AreaAspect.class);
 
	/**
	 * 区域缓存更新
	 */
	 @AfterReturning(
		 "execution(* cc.messcat.web.system.AreaController.addarea(cc.messcat.entity.area.Area,javax.servlet.http.HttpSession))"
	 	+ "||execution(* cc.messcat.web.system.AreaController.updatearea(java.lang.Long,java.lang.String,java.lang.String,java.lang.Long,javax.servlet.http.HttpSession))"
	 	+ "||execution(* cc.messcat.web.system.AreaController.delectarea(java.lang.Long,javax.servlet.http.HttpSession))"
	 	+ "")
	public void updateAreaCacha() {
		logger.info("区域缓存更新");
		
		Cache cache = manager.getCache("areaCache");
		List<Area> allArea = areaService.getAllArea();
		Map<Long,List<Area>> map = new HashMap<>();
		for (Area area : allArea) {
			List<Area> list = map.get(area.getFatherId());
			if(Collections.isEmpty(list)) {
				list = new ArrayList<Area>();
			} 
			list.add(area);
			map.put(area.getFatherId(),list);
		}
		cache.remove("allAreaByFatherId");
		cache.put(new Element("allAreaByFatherId", map));
	}

}
